<?php

class PushServer
{
    private static $instance = null;
    private static $server = null;
    private $messageHandler = null; //处理消息的对象

    private function __construct()
    {
        var_dump('The swoole server is working!!!');

        //创建websocket服务器对象，监听0.0.0.0:9502端口
        self::$server = new swoole_websocket_server("0.0.0.0", 9502);


        require "./MessageHandler.php";
        $this->messageHandler = new MessageHandler();

        //注册事件
        self::$server->on("open",[$this,'onOpen']);
        self::$server->on("message",[$this,'onMessage']);
        self::$server->on("close",[$this,'onClose']);
        self::$server->on("request",[$this,'onrequest']);
//        self::$server->on("WorkerStart",[$this,'onWorkerStart']);
    }


    public static function getInstance(){
        if(!self::$instance instanceof  self){
            self::$instance = new self();
        }
        return self::$instance;
    }

    //启动服务器
    public function start(){
        self::$server->start();
    }

    /**
     * 监听WebSocket连接打开事件
     * $server : websocket服务器对象
     * $request : 客户端的请求
     * $request->fd : 客户端的唯一编号
     */
    public function onOpen(Swoole\WebSocket\Server $server,$request){
        var_dump($request->fd);
    }


    /*
     * 监听WebSocket消息事件
     * 客户端向服务器发送消息时调回调函数
     * $server : websocket服务器对象
     * $frame :客户端发送的
     * $frame->fd : 客户端的唯一编号
     * $frame->data : 客户端发送的文文枉本内*
     * $server->push(客户端的唯一编号，消息 //服务器向指定端发送消息
     *
     */
    public function onMessage(Swoole\WebSocket\Server $server, $frame){
        $data = json_decode($frame->data,true);
        var_dump($data);
        if(method_exists($this->messageHandler,$data['method_name'])){
            call_user_func([$this->messageHandler,$data['method_name']],$frame->fd,$data);
        }
    }


    public function onClose($server,$fd){

    }

    public function onrequest(Swoole\Http\Request $request, Swoole\Http\Response $response){
        var_dump('This is request!');
    }

    //swoole的函数，服务启动后后自动执行
    public function onWorkerStart(){
        echo "xiaojing on workerStart...........................".microtime()."\n";

        require "./MessageHandler.php";
        $this->messageHandler = new MessageHandler();
    }

}

PushServer::getInstance()->start();